﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using MiscUtil;
using Kise.LprCapturer;

namespace DataReceiver
{
    public partial class Form1 : Form
    {
        private const string _fileName = "ip.txt";
        private const string _laneConfigFileName = "车道配置.txt";
        private LprCapturer _lprCapturer;
        private bool _connectStarted = false;
        private IpEndpoint[] _Ips = new IpEndpoint[0];

        public Form1()
        {
            InitializeComponent();


            _lprCapturer = new LprCapturer();
            _lprCapturer.LprCapturerEnabled = true;
            _lprCapturer.ProvienceCharacter = Properties.Settings.Default.HiChar; //设置汉字优先级，在四川就设置"川"
            _lprCapturer.TagetDir = Properties.Settings.Default.TargetDir; //图片保存目录
            _lprCapturer.FilePathFormatString = Properties.Settings.Default.FilePathFormatString; //图片命名格式
            _lprCapturer.SaveImage = checkBoxSave.Checked; //是否保存图片
            _lprCapturer.NewLprCaptured += ReceiverOnNewFrameReceived; //接收到车牌的通知事件，当收到车牌是就会收到通知
            _lprCapturer.H264FrameReceived += LprCapturerOnH264FrameReceived; //接收到h264帧的通知事件，当每收到一帧h264时就会触发，在该处理函数中处理h264帧(保存录像或者解码显示)


        }

        private void LprCapturerOnH264FrameReceived(object sender, EventArgs<H264Frame> eventArgs)
        {
            var h264 = eventArgs.Value;
            System.Diagnostics.Debug.WriteLine(
                "h264: " + h264.LocationId +
                " at: " + h264.CaptureTime.ToLongTimeString() +
                " roadid: " + h264.RoadNo +
                " len: " + h264.H264.Length +
                (Kise.LprCapturer.Helper.IsH264Header(h264.H264) ? " (header)" : string.Empty));
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            CloseSocket();

            if (!_connectStarted)
            {

                foreach (var ipEndpoint in _Ips)
                {
                    var ep = new IPEndPoint(IPAddress.Parse(ipEndpoint.IpAddress), ipEndpoint.Port);
                    _lprCapturer.AddEndPoint(ep); //添加一路新摄像机
                }

                buttonConnect.Text = "断开";
                _connectStarted = true;
            }
            else
            {
                CloseSocket();
                buttonConnect.Text = "连接";
                _connectStarted = false;
            }
        }


        private void CloseSocket()
        {
            if (_lprCapturer != null)
            {
                _lprCapturer.StopAllEndPoint(); //断开所有摄像机
            }
        }

        private void ReceiverOnNewFrameReceived(object sender, EventArgs<LprCaptured> eventArgs)
        {
            var img = Image.FromStream(new MemoryStream(eventArgs.Value.JpegBuffers[0]));
            Action ac = () =>
                            {
                                var old = this.pictureBox1.Image;
                                this.pictureBox1.Image = img;
                                if (old != null)
                                {
                                    old.Dispose();
                                }

                                labelLaneNumber.Text = eventArgs.Value.RoadNo.ToString(CultureInfo.InvariantCulture);
                                labelLprNumber.Text = eventArgs.Value.LprNumber;
                                labelSpeed.Text = eventArgs.Value.Speed.HasValue ?
                                    eventArgs.Value.Speed.Value.ToString(CultureInfo.InvariantCulture) : string.Empty;

                            };
            this.BeginInvoke(ac);
        }

        private void checkBoxSave_CheckedChanged(object sender, EventArgs e)
        {
           
            if (_lprCapturer != null)
            {
                _lprCapturer.SaveImage = checkBoxSave.Checked;
            }
        }

        

        private void SaveSettings()
        {
            Properties.Settings.Default.HiChar = textBoxHiChar.Text;
            //Properties.Settings.Default.IPPort = textBoxIpPort.Text;
            Properties.Settings.Default.SavePic = checkBoxSave.Checked;

            Properties.Settings.Default.Save();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBoxHiChar.Text = Properties.Settings.Default.HiChar;
            //textBoxIpPort.Text = Properties.Settings.Default.IPPort;
            checkBoxSave.Checked = Properties.Settings.Default.SavePic;

            try
            {
                if (File.Exists(_fileName))
                {
                    var engine = new FileHelpers.DelimitedFileEngine<IpEndpoint>();
                    _Ips = engine.ReadFile(_fileName);
                }

                if (File.Exists(_laneConfigFileName))
                {
                    var engine = new FileHelpers.FileHelperEngine<LaneConfig>();
                    var laneConfigs = engine.ReadFile(_laneConfigFileName);
                    _lprCapturer.LaneConfigs = laneConfigs;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "读取配置文件发生异常\r\n\r\n" + ex, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.buttonConnect_Click(this.buttonConnect, EventArgs.Empty);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveSettings();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (var form = new FormOptions())
            {
                if (form.ShowDialog(this) == DialogResult.OK)
                {
                    if (_lprCapturer != null)
                    {
                        _lprCapturer.TagetDir = Properties.Settings.Default.TargetDir;
                        _lprCapturer.FilePathFormatString = Properties.Settings.Default.FilePathFormatString;
                    }
                }
            }
        }

        private void buttonIpSettings_Click(object sender, EventArgs e)
        {
            using (var form = new FormConnections())
            {
                form.IPs = _Ips.ToList();
                if (form.ShowDialog(this) == DialogResult.OK)
                {
                    var ips = form.IPs;
                    _Ips = ips.ToArray();

                    SaveIps();
                }

            }
        }

        private void SaveIps()
        {
            var engine = new FileHelpers.DelimitedFileEngine<IpEndpoint>();
            engine.WriteFile(_fileName, _Ips);
        }

        private void buttonConfigLanes_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start(_laneConfigFileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            
        }
    }
}
